import 'package:flutter/material.dart';

@immutable
class AnimatedSearchBar extends StatefulWidget {
  @override
  _AnimatedSearchBarExampleState createState() => _AnimatedSearchBarExampleState();

  void Function(String) onSearch;

  AnimatedSearchBar({required this.onSearch});

}

class _AnimatedSearchBarExampleState extends State<AnimatedSearchBar> {
  late final TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: 4,
      borderRadius: BorderRadius.circular(30),
      child: TextField(
        controller: _controller,
        onChanged: (_) => setState(() {}),
        onSubmitted: widget.onSearch,
        decoration: InputDecoration(
          hintText: '搜索地点',
          hintStyle: TextStyle(color: Colors.grey[500]),
          prefixIcon: const Icon(Icons.search, color: Colors.grey),
          suffixIcon: _controller.text.isNotEmpty
              ? IconButton(
            icon: const Icon(Icons.clear, color: Colors.grey),
            onPressed: _clearInput,
          )
              : null,
          filled: true,
          fillColor: Colors.grey[100],
          contentPadding: const EdgeInsets.symmetric(
              vertical: 12, horizontal: 16),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(30),
            borderSide: BorderSide.none,
          ),
        ),
        style: const TextStyle(fontSize: 16),
      ),
    );
  }
  void _clearInput() {
    _controller.clear();
    setState(() {});
  }
}